home *** CD-ROM | disk | FTP | other *** search
- Path: rain.fr!world-net!usenet
- From: Frederic LACHASSE <lachass@worldnet.fr>
- Newsgroups: comp.lang.c++,rb.technical
- Subject: Re: Can copy constructor and operator= share code?
- Date: Sat, 02 Mar 1996 23:18:20 +0000
- Organization: World-Net information exchange, Internet provider.
- Message-ID: <VA.00000053.00cdab05@fred>
- References: <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM>
- Reply-To: lachass@worldnet.fr
- NNTP-Posting-Host: pm9-025.sct.fr
- X-Newsreader: Virtual Access by Ashmount Research Ltd, http://www.ashmount.com
-
- In article <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM>, borisb@sd.znet.com
- (Boris Burtin) wrote:
- >
- > I have noticed that a copy constructor and operator= perform pretty
- > much the same function. The code I wrote for my class simply copies
- > each member variable from one class to the other.
- >
- > Is there a way for the one of the two functions to call the other, to
- > avoid duplicate code? I have tried calling the copy constructor from
- > operator=, but nothing happens. I've gotten around this problem by
- > creating a private Copy() function, which is called by both the copy
- > constructor and operator=. Is there another way?
- >
-
- Generally, the operator=() must release old resource and create a copy
- of the other object. So a generic operator=() can be:
-
- T &T::operator =(const T &t)
- {
- if (this != &t) // if objects are same, nothing to do
- {
- ~T(); // explicit call to destructor to release resources.
- new(this) T(t); // use of the placement operator to call the
- // copy constructor.
- }
- }
-
- Some times though, the assignement operator can be optimize to reuse
- resources of the old object.
-
- Frederic LACHASSE (ECP 86)
- CompuServe: 100530,2005
- Internet: lachass@worldnet.fr
-
-